const fs = require('fs')
const path = require('path')
const uploadUrl="http://localhost:3000";
const { UserInfoUpdate } = require('../model/userModel.js')
module.exports = {
	file: async (ctx, next) => {
		// token里的用户id
		const { user_id } = ctx.state.data
		const file = ctx.request.files.file;
		const reader = fs.createReadStream(file.path);
		let fileType = file.type
		let filePath =path.resolve("uploadFile");
		// 可以根据时间戳自定义
		// file.name = ;
		// 根据文件类型存入对应的文件夹
		let fileResource = path.join(filePath,`/file/${file.name}`);;
		let url = `/file/${file.name}`
		if(fileType.match('image')){
		    fileResource = path.join(filePath,`/image/${file.name}`);
		    url = `/image/${file.name}`
		}else if(fileType.match('audio')){
		    fileResource = path.join(filePath,`/voice/${file.name}`);
		    url = `/voice/${file.name}`
		}
		const headImgUrl = uploadUrl + url
		if (!fs.existsSync(filePath)) { //判断uploadFile文件夹是否存在，如果不存在就新建一个
		    fs.mkdir(filePath, (err) => {
		        if (err) {
		            throw new Error(err)
		        } else {
		            let upstream = fs.createWriteStream(fileResource);
		            reader.pipe(upstream);
		            ctx.body = {
						code:200,
						data:{
							name:`${file.name}`,
							type:fileType,
							url: headImgUrl
						}
		            }
		        }
		    })
		} else {
		    let upstream = fs.createWriteStream(fileResource)
		    reader.pipe(upstream);
		    ctx.body = {
				code:200,
				data:{
					name:`${file.name}`,
					type:fileType,
					url: headImgUrl
				}
		    }
		}
		
	}
}
